<?php
App::uses('SimpleImage', 'Lib');
class Foto extends AppModel {
    public $name = 'Foto';
	public $useTable = false; 
	
	
	public function findAll($dir = null){
		$fotos = array();
		$image = new SimpleImage();
		$dirBase = 'img\\albunes\\' . $dir;
		$dirFoto = 'albunes/' . $dir . '/';
		if (is_dir($dirBase)) {
			if ($gd = opendir($dirBase)) {
				while ($file = readdir($gd)) {
					if ($this->esImagen($file) && !$this->startsWith($file, 'mini_')) {
						if(!file_exists(WWW_ROOT.$dirBase.'\\mini_'.$file)){
							$image->load(WWW_ROOT.$dirBase.'\\'.$file);
							$image->resizeToWidth(298);
							$image->save(WWW_ROOT.$dirBase.'\\mini_'.$file);
							$this->cortarImagen(WWW_ROOT.$dirBase.'\\mini_'.$file);
						}
						$fotos[] = array('foto' => array('nombre' => $dirFoto . $file,
														'mini' => $dirFoto.'mini_'.$file));
					}
				}
				closedir($gd);
			}
		}
		return $fotos;
	}
	
	public function startsWith($haystack, $needle) {
		$length = strlen($needle);
		return (substr($haystack, 0, $length) === $needle);
	}
	
	function esImagen($fichero) {
       $fichero = strtolower($fichero) ;
       $extension = split("[/\\.]", $fichero) ;
       $n = count($extension)-1;
       $extension = $extension[$n];
	   return ($extension == "jpg" || $extension == "jpeg" || $extension == "gif" || $extension == "png" || $extension == "pneg");
	   
	} 
	
	public function cortarImagen($filename){
		// This will be the final size of the image (e.g. how many pixels
		// left and down we will be going)
		$crop_width = 298;
		$crop_height = 172;
		// Get dimensions of the original image
		list($current_width, $current_height) = getimagesize($filename);
		$top = 0;
		if($current_height > $crop_width){
			$top = $current_height - $crop_width;
			$top = round($top/2);
		
		}
		$left = 0;
		// Resample the image
		$canvas = imagecreatetruecolor($crop_width, $crop_height);
		$current_image = imagecreatefromjpeg($filename);
		imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
		imagejpeg($canvas, $filename, 100);
	}
	
	
}